<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace Model\UserBundle\Model;

use Base\BaseModel;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Model\UserBundle\Setting\UserSetting;

class UserModel extends BaseModel{


    /*
     * 列表基本设置【通用模块必须】
     */
    public function listSettingDefault()
    {
        $settings = new UserSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    /**
     * @param string $account
     * @return int
     */
    public function checkAccountForNew($account)
    {//检查账号是否被占用
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("user")->where("account = :account")->setParameter("account",$account);
        return $qb->execute()->rowCount();
    }

    /**
     * @param $account
     * @param $password
     * @return bool|mixed
     */
    public function checkAccountPassword($account, $password)
    {//检查账号密码
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("user")
            ->where("account = :account")->setParameter("account",$account)
            ->andWhere("password = :password")->setParameter("password",$password);
        if ($qb->execute()->rowCount() == 1) {
            return $qb->execute()->fetch();
        } else {
            return false;
        }
    }

    /**
     * @param array $defaultInsertData 默认值
     * @param array $frontData 前台数据
     */
    public function checkAndSetUserParent(&$defaultInsertData ,$frontData )
    {//检查推荐人及设置
        $settings = new UserSetting($this->getDoctrine());
        $fieldSet = $settings->inviteSetKey;
        if (isset($frontData[$fieldSet])) {
            $parent = $frontData[$fieldSet];
            $qb = $this->getQueryBuilder();
            $fieldGet = $settings->inviteGetKey;
            $qb->select("*")->from("user")->where("$fieldGet = :$fieldGet")->setParameter("$fieldGet",$parent);
            $count = $qb->execute()->rowCount();
            if ( $count ) {
                $defaultInsertData[$fieldSet] = $parent;
            }
        }
    }

    /**
     * @param array $defaultInsertData 默认值
     * @param array $frontData 前台数据
     * @return bool
     */
    public function commInsert($defaultInsertData,$frontData)
    {//通用数据插入[含推荐人判断及设置]
        $qb = $this->getQueryBuilder();
        $qb->insert("user");
        $this->checkAndSetUserParent( $defaultInsertData ,$frontData);
        foreach ($defaultInsertData as $key => $val) {
            if (isset($frontData[$key])) {
                $qb->setValue("$key",":$key")->setParameter("$key",$frontData[$key]);
            } else {
                $qb->setValue("$key",":$key")->setParameter("$key",$val);
            }
        }
        $qb->execute();
        if ($qb->getState()) {return true;} else {return false;}
    }

    /**
     * @param $frontData
     * @param $groups
     * @return bool
     */
    public function commReg($frontData,$groups = 3)
    {//普通注册，需账号、密码、安全密码和用户组
        //注册所需基本字段及默认值
        $defaultInsertData = array(
            "account"   => "",
            "password"  => "",
            "passwordPay"  => "",
            "groups"  => $groups,
            "addTime"  => time(),
            "headPic"  => "/public/default_user.png",
            "level"  => 0,
            "parent"  => 0,
//            "roles" => json_encode($this->getUserRolesByGroups($groups))
        );
        return $this->commInsert($defaultInsertData,$frontData);
    }

    /**
     * @param $account
     * @param $password
     * @param $loginInfo
     * @return bool|mixed
     */
    public function commLogin($account,$password,$loginInfo)
    {
        if ($userInfo = $this->checkAcountPassword($account,$password))
        {//账号密码匹配成功
            $loginInfo["passwordError"] = 0;
            $this->updateUserInfo($userInfo["id"],array(
                "lastLoginTime" =>time(),
                "lastLoginIp"   =>$loginInfo["loginIp"],
            ));
        }
        else
        {//账号密码错误
            $loginInfo["passwordError"] = 1;
        }
        $userLoginLogModel = new UserLoginLogModel($this->getDoctrine());
        $userLoginLogModel->addLoginLog($loginInfo);
        return $userInfo;
    }

    /**
     * @param $userId
     * @return array
     */
    public function getUserRolesByUser($userId)
    {//获取用户角色
        $user = $this->getUserInfo($userId);
        if ($user && isset($user["groups"])) {
            $userGroups = $user["groups"];
            $Roles = $this->getUserRolesByGroups($userGroups);
            return $Roles;
        } else {
            return array();
        }
    }

    /**
     * @param $userGroups
     * @return array
     */
    public function getUserRolesByGroups($userGroups)
    {//获取分组角色
        $qb = $this->getQueryBuilder();
        $qb->select("Role.code")
            ->from("UserGroupsRole","UserGroupsRole")
            ->where("UserGroupsRole.groups = :groups")->setParameter("groups",$userGroups)
            ->leftJoin("UserGroupsRole","Role","Role","UserGroupsRole.role = Role.id")
        ;
        $UserGroupsRole =  $qb->execute()->fetchAll();
        $Roles = array();
        foreach ($UserGroupsRole as $row) {
            $Roles[] = $row["code"];
        }
        return $Roles;
    }

    /**
     * @param $userId
     * @return mixed
     */
    public function getUserInfo($userId)
    {//获取用户信息
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("user")->where("id = :id")->setParameter("id",$userId);
        return $qb->execute()->fetch();
    }

    /**
     * @param int $userId
     * @param array $userInfo
     */
    public function updateUserInfo($userId,$userInfo)
    {//更新个人信息
        $qb = $this->getQueryBuilder();
        $qb->update("user");
        foreach ($userInfo as $key => $val) {
            $qb->set($key,":$key")->setParameter("$key",$val);
        }
        $qb->where("id = :id")->setParameter("id",$userId);
        $qb->execute();
    }


}